<template>
    <div>
        <!-- 还款情况:fzHkqk-->
        <div class="w_100 headTips d_f j_c_s_b">
            <div class="d_f a_i_c">
                <div class="line"></div>
                {{ name }}
            </div>
            <div class="isClose" @click="close">
                <el-icon v-if="type == 'smallForm'">
                    <CloseBold />
                </el-icon>
            </div>
            <el-switch v-if="type == 'bigForm'" @change="change" v-model="status"
                style="--el-switch-on-color: #13ce66;" />
            <el-button type="primary" v-if="type == 'useForm' && isReset == 1" @click="clearForm">清除表单</el-button>
        </div>
        <div class="formBox fzHkqk">
            <div class="fzHkqk_form">
                <myform :fields="fields" ref="form1" :rules="rules" :model="model.repayment" :options="options"
                    class="m_t_16">
                </myform>
            </div>
            <div v-if="model.repayment.repaymentStatus == '0'">
                <div class="segment"></div>
                <div class="formArrow d_f a_i_c m_t_30">
                    <img src="../../assets/formArrow.png" alt="">
                    <span>盖章版担保责任解除函上传</span>
                </div>
                <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                    :before-upload="beforeUpload" :on-success="securitySuccess" multiple :limit="100000000">
                    <el-button class="m_t_16" :icon="Upload" :disabled="type == 'useForm'&&!isAudit ? false : true"
                        type="primary">上传凭证</el-button>
                </el-upload>
                <mytable :fields="fields3" width="150" ref="tableRef" :defaultList="model.repayment.releaseList"
                    class="m_t_16" :isSelection="false" :isPaginationShow="false">
                    <template v-slot:operation="{ row, $index }">
                        <div class="d_f j_c_s_b">
                            <span class="success" @click="preview(row)">预览</span>
                            <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                                :before-upload="beforeUpload" :on-success="securitySuccess1" multiple
                                :limit="100000000">
                                <span class="edit" @click="reUpload($index)" v-if="!isAudit">重新上传</span>
                            </el-upload>

                            <span class="error" @click="deleteSecurity($index)" v-if="!isAudit">删除</span>
                        </div>
                    </template>
                </mytable>
            </div>
            <div class="fzHkqk_form1" v-if="model.repayment.repaymentStatus == '1'">
                <myform :fields="fields1" ref="form1" :rules="rules" @handleSelect="handleSelect" :model="model.repayment" :options="options"
                    class="m_t_16">
                </myform>
                <div class="segment"></div>
                <div class="formArrow d_f a_i_c m_t_30">
                    <img src="../../assets/formArrow.png" alt="">
                    <span>盖章版贷款逾期通知书上传</span>
                </div>
                <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                    :before-upload="beforeUpload" :on-success="beOverdueSuccess" multiple :limit="100000000">
                    <el-button class="m_t_16" :icon="Upload" :disabled="type == 'useForm' ? false : true"
                        type="primary">上传通知书</el-button>
                </el-upload>
                <mytable :fields="fields3" width="150" ref="tableRef" :defaultList="model.repayment.overdueNoticeList"
                    class="m_t_16" :isSelection="false" :isPaginationShow="false">
                    <template v-slot:operation="{ row, $index }">
                        <div class="d_f j_c_s_b">
                            <span class="success" @click="preview(row)">预览</span>
                            <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                                :before-upload="beforeUpload" :on-success="beOverdueSuccess1" multiple
                                :limit="100000000">
                                <span class="edit" @click="reUpload($index)">重新上传</span>
                            </el-upload>

                            <span class="error" @click="deleteBeOverdue($index)">删除</span>
                        </div>
                    </template>
                </mytable>
            </div>
            <div v-if="model.repayment.repaymentStatus == '2'">
                <myform :fields="fields2" ref="form1" :rules="rules" :model="model.repayment"
                    :options="options" class="m_t_16">
                </myform>
            </div>
            <div class="segment" v-if="fields4.length > 0"></div>
            <div class="formArrow d_f a_i_c m_t_30" v-if="fields4.length > 0">
                <img src="../../assets/formArrow.png" alt="">
                <span>{{ subTitle || '新加字段' }}</span>
            </div>
            <div v-if="fields4.length > 0">
                <myform :fields="fields4" :model="model.repayment" :options="options" class="m_t_16">
                </myform>
            </div>
        </div>
    </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { fzHkqkType } from './data'
import { copy, fileFormat, momentNewDate } from '../../utils/date'
import { formGet, unitFormSet } from '../../api/system/flowPath'
import { listByParentArr } from '../../api/login'
import { Message } from '../../utils/resetMessage'
import { useRouter } from 'vue-router'
import { CloseBold, Upload } from '@element-plus/icons-vue'
import { httpConfig } from '../../utils/config'
import { NUMBRT_REG, INTEGER } from '../../utils/regular'
import moment from 'moment'
const model = {
    repayment: {
        repaymentStatus: '0',//还款状态：0-结清，1-逾期，2-展期
            overdueMoney: '',//逾期金额
            overdueStart: '',//逾期起始日期
            overdueDays: '',//逾期天数
            nowAddress: '',//借款人现住址
            // isNow: '1',
            overdueRemark: '',//逾期情况说明
            // guaMoney: '',//展期金额
            // period: '',//期限
            // guaranteeRate: '',//担保费率
            // premium: '',//应缴保费
            // isNow: '1',
        approvalRemark: '',
        releaseList: [],
        overdueNoticeList: [],
        isReview: 1,
        
    },
    otherDeleteData: [],
}
export default defineComponent({
    name: '',
    props: {
        type: {
            type: String,
            default: '',
        },
        unitId: {
            type: [String, Number],
            default: '',
        },
        isEnabled: {
            type: Number,
            default: '',
        },
        nodeObj: {
            type: Object,
            default: {}
        },
        vars: {
            type: Object,
            default: {}
        },
        isAudit: {
            type: Boolean,
            default: false
        }
    },
    components: {
        CloseBold
    },
    setup(props: any) {
        const data: fzHkqkType = reactive({
            model: copy(model),
            status: true,
            id: '',
            name: '还款情况',
            subTitle: '',
            index: 0,
            options: {
                repaymentStatus: [
                    {
                        name: '结清',
                        id: '0'
                    },
                    {
                        name: '逾期',
                        id: '1'
                    },
                    {
                        name: '展期',
                        id: '2'
                    },
                ],
                isNow: [
                    {
                        name: '是',
                        id: '1'
                    },
                    {
                        name: '否',
                        id: '2'
                    }
                ],
            },
            fields: [
                {
                    label: "还款情况",
                    prop: 'repaymentStatus',
                    placeholder: '请选择还款情况',
                    type: 'radio',
                    labelWidth: '150px',
                    disabled:false,
                },
                {
                    label: "意见备注",
                    prop: 'approvalRemark',
                    placeholder: '请输入意见备注',
                    type: 'textarea',
                    labelWidth: '150px',
                    disabled:false,
                },
            ],
            fields1: [
                {
                    label: "逾期金额",
                    prop: 'overdueMoney',
                    placeholder: '请输入逾期金额',
                    type: 'input',
                    labelWidth: '150px',
                    unit: '元',
                    disabled:false,
                },
                {
                    label: "逾期起始日期",
                    prop: 'overdueStart',
                    placeholder: '请选择逾期起始日期',
                    type: 'date',
                    labelWidth: '150px',
                    disabled:false,
                },
                {
                    label: "至今逾期天数",
                    prop: 'overdueDays',
                    placeholder: '请输入至今逾期天数',
                    type: 'number',
                    labelWidth: '150px',
                    unit: '天',
                    disabled:false,
                },
                {
                    label: "借款人现住址",
                    prop: 'nowAddress',
                    placeholder: '请输入借款人现住址',
                    type: 'input',
                    labelWidth: '150px',
                    disabled:false,
                },
                // {
                //     label: "是否在途",
                //     prop: 'isNow',
                //     placeholder: '请选择',
                //     type: 'radio',
                //     labelWidth: '150px'
                // },
                {
                    label: "逾期情况说明",
                    prop: 'overdueRemark',
                    placeholder: '请输入逾期情况说明',
                    type: 'textarea',
                    labelWidth: '150px',
                    disabled:false,
                },
            ],
            fields2: [
                // {
                //     label: "展期金额",
                //     prop: 'guaMoney',
                //     placeholder: '请输入展期金额',
                //     type: 'input',
                //     labelWidth: '150px',
                //     unit: "元",
                //     disabled:false,
                // },
                // {
                //     label: "期限",
                //     prop: 'period',
                //     placeholder: '请输入期限',
                //     type: 'number',
                //     labelWidth: '150px',
                //     unit: '个月',
                //     disabled:false,
                // },
                // {
                //     label: "担保费率",
                //     prop: 'guaranteeRate',
                //     placeholder: '请输入担保费率',
                //     type: 'input',
                //     labelWidth: '150px',
                //     unit: '%',
                //     disabled:false,
                // },
                // {
                //     label: "应缴保费",
                //     prop: 'premium',
                //     placeholder: '请输入应缴保费',
                //     type: 'input',
                //     labelWidth: '150px',
                //     unit: "元",
                //     disabled:false,
                // },
                // {
                //     label: "是否在途",
                //     prop: 'isNow',
                //     placeholder: '请选择',
                //     type: 'radio',
                //     labelWidth: '150px'
                // },

            ],
            fields3: [
                {
                    label: '资料名称',
                    prop: 'businessDataName',
                },
                {
                    label: '上传环节',
                    prop: 'nodeName',
                },
                {
                    label: '上传人',
                    prop: 'uploadName',
                },
                {
                    label: '上传时间',
                    prop: 'uploadTime',
                },
            ],
            fields4: [],
            action: httpConfig.upload,
            headers: {
                token: localStorage.getItem('Token')
            },
            rules: {
                repaymentStatus: [
                    { required: true, message: '请选择还款情况', trigger: 'change' },
                ],
                guaMoney: [
                    { required: true, message: '请输入展期金额', trigger: 'blur' },
                    { pattern: NUMBRT_REG, message: '展期金额格式不正确' }
                ],
                period: [
                    { required: true, message: '请输入期限', trigger: 'blur' },
                    { pattern: INTEGER, message: '期限格式不正确' }
                ],
                guaranteeRate: [
                    { required: true, message: '请输入担保费率', trigger: 'blur' },
                    { pattern: NUMBRT_REG, message: '担保费率格式不正确' }
                ],
                premium: [
                    { required: true, message: '请输入应缴保费', trigger: 'blur' },
                    { pattern: NUMBRT_REG, message: '应缴保费格式不正确' }
                ],
                overdueMoney: [
                    { required: true, message: '请输入逾期金额', trigger: 'blur' },
                    { pattern: NUMBRT_REG, message: '逾期金额格式不正确' }
                ],
                overdueStart: [
                    { required: true, message: '请输入逾期起始日期', trigger: 'blur' },
                ],
                overdueDays: [
                    { required: true, message: '请输入逾期天数', trigger: 'blur' },
                    { pattern: NUMBRT_REG, message: '逾期天数格式不正确' }
                ],
                nowAddress: [
                    { required: true, message: '请输入借款人现住址', trigger: 'blur' },
                ],
                // overdueRemark: [
                //     { required: true, message: '请输入逾期情况说明', trigger: 'blur' },
                // ],
                // approvalRemark: [
                //     { required: true, message: '请输入意见备注', trigger: 'blur' },
                // ],
                // isNow: [
                //     { required: true, message: '请选择', trigger: 'blur' },
                // ],
            },
            isReset: 2,
        })
        const router = useRouter()
        const form1 = ref()
        onBeforeMount(() => {
            methods.getData()
            data.status = props.isEnabled == 0 ? false : true
        })
        const methods = {
            close() {
                router.push('/system/flowPath/childForm/index')
            },
            //获取自定义表单
            getData() {
                formGet({ tag: 'fzHkqk' }).then((res: any) => {
                    data.id = res.id
                    data.name = res.name
                    data.isReset = res.isReset
                    if (!res.formStruct || res.formStruct == 'null' || res.formStruct == '{}') return
                    data.subTitle = res.subTitle
                    let formStruct = JSON.parse(res.formStruct)
                    formStruct.formFields.map((item:any)=>{
                        data.model.repayment[item.prop]=''
                    })
                    data.fields4 = formStruct.formFields
                    data.fields.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    data.fields1.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    data.fields2.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    data.fields4.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    if (props.vars) {
                        const localData = props.vars
                        for (let key in data.model.repayment) {
                            if(localData.repayment[key]!=null){
                                data.model.repayment[key] = localData.repayment[key]
                            }
                        }
                        data.model.repayment.releaseList=localData.repayment.releaseList||[]
                        data.model.repayment.overdueNoticeList=localData.repayment.overdueNoticeList||[]
                        if(props.type=='useForm'){
                          data.model.repayment.approvalRemark=''
                        }
                        if(data.model.repayment.repaymentStatus!=null){
                            data.model.repayment.repaymentStatus=String(data.model.repayment.repaymentStatus)
                        }
                    } 
                    let arr = formStruct.formFields.filter((item: any) => {
                        return item.type == 'select'
                    })
                    let ids = arr.map((item: any) => {
                        return item.prop
                    })
                    methods.handleSelect('overdueStart')
                    if (ids.length == 0) return
                    listByParentArr({ ids: ids }).then((res: any) => {
                        ids.map((item: any) => {
                            data.options[item] = res[item]
                        })
                    })
                })
            },
            //设置表单的启用跟停用
            change() {
                unitFormSet({ isEnabled: data.status ? 1 : 0, id: data.id, unitId: props.unitId }).then(() => {
                    Message({ type: 'success', message: '设置成功' })
                }).catch(() => {
                    data.status = !data.status
                })
            },
            handleSelect(prop:string){
                if(prop=='overdueStart'){
                let day =moment(new Date()).diff(data.model.repayment.overdueStart,'days')
                if(day>-1){
                    data.model.repayment.overdueDays=day
                }else{
                    data.model.repayment.overdueDays='0'
                }
                }
            },
            //文件上传之前校验格式
            beforeUpload(file: any) {
                return fileFormat(file, ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg', 'JPG', 'zip', 'txt', 'pptx', 'gif', 'rar', 'ppt','PNG','JPEG'], '')
            },
            //上传盖章版担保责任解除函
            securitySuccess(e: any, file: any) {
                let obj: any = {
                    fileUrl: e.data,
                    uploadName: JSON.parse(<string>localStorage.getItem('userVO')).name,
                    uploadTime: momentNewDate(),
                    businessDataName: file.name,
                    nodeName: props.nodeObj.name,
                    nodeId: props.nodeObj.id,
                }
                data.model.repayment.releaseList.push(obj)
            },
            //上传盖章版担保责任解除函
            securitySuccess1(e: any, file: any) {
                if (data.model.repayment.releaseList[data.index].nodeId) {
                    data.model.otherDeleteData.push({ delNodeId: data.model.repayment.releaseList[data.index].nodeId })
                }
                data.model.repayment.releaseList[data.index].fileUrl = e.data,
                    data.model.repayment.releaseList[data.index].businessDataName = file.name
                data.model.repayment.releaseList[data.index].uploadName = JSON.parse(<string>localStorage.getItem('userVO')).name
                data.model.repayment.releaseList[data.index].uploadTime = momentNewDate()
                data.model.repayment.releaseList[data.index].nodeName = props.nodeObj.name
                data.model.repayment.releaseList[data.index].nodeId = props.nodeObj.id
            },
            //删除盖章版担保责任解除函
            deleteSecurity(index: number) {
                console.log(data.model);
                if (data.model.repayment.releaseList[index].nodeId) {
                    data.model.otherDeleteData.push({ delNodeId: data.model.repayment.releaseList[index].nodeId })
                }
                data.model.repayment.releaseList.splice(index, 1)
            },
            beOverdueSuccess(e: any, file: any) {
                let obj: any = {
                    fileUrl: e.data,
                    uploadName: JSON.parse(<string>localStorage.getItem('userVO')).name,
                    uploadTime: momentNewDate(),
                    businessDataName: file.name,
                    nodeName: props.nodeObj.name,
                    nodeId: props.nodeObj.id,
                }
                data.model.repayment.overdueNoticeList.push(obj)
            },
            beOverdueSuccess1(e: any, file: any) {
                if (data.model.repayment.overdueNoticeList[data.index].nodeId) {
                    data.model.otherDeleteData.push({ delNodeId: data.model.repayment.overdueNoticeList[data.index].nodeId })
                }
                data.model.repayment.overdueNoticeList[data.index].fileUrl = e.data,
                    data.model.repayment.overdueNoticeList[data.index].businessDataName = file.name
                data.model.repayment.overdueNoticeList[data.index].uploadName = JSON.parse(<string>localStorage.getItem('userVO')).name
                data.model.repayment.overdueNoticeList[data.index].uploadTime = momentNewDate()
                data.model.repayment.overdueNoticeList[data.index].nodeName = props.nodeObj.name
                data.model.repayment.overdueNoticeList[data.index].nodeId = props.nodeObj.id
            },
            deleteBeOverdue(index: number) {
                if (data.model.repayment.overdueNoticeList[index].nodeId) {
                    data.model.otherDeleteData.push({ delNodeId: data.model.repayment.overdueNoticeList[index].nodeId })
                }
                data.model.repayment.overdueNoticeList.splice(index, 1)
            },
            //预览文件
            preview(row: any) {
                window.open(row.fileUrl, '_blank')
            },
            //重新上传
            reUpload(index: number) {
                data.index = index
            },
            //清除表单数据
            clearForm() {
                data.model = copy(model)
            },
            resultData() {
                return new Promise((resolve, reject) => {
                    form1.value.verification().then((res) => {
                        resolve(data.model)
                    }).catch(() => {
                        reject(false)
                    })
                })
            },
            saveData() {
                return new Promise((resolve, reject) => {
                    resolve(data.model)
                })
            },
        }
        return {
            ...toRefs(data),
            ...methods, form1, Upload
        }
    }
})
</script>
<style lang='scss'>
.fzHkqk {
    .el-form-item {
        width: 50% !important;
        margin-right: 0px !important;

        .el-form-item__content {
            width: calc(100% - 200px) !important;

            .el-input,
            .el-cascader,
            .el-select {
                width: 100% !important;
            }
        }
    }
}

.fzHkqk_form {

    .el-form-item:nth-child(1),
    .el-form-item:nth-child(2) {
        width: 100% !important;
    }
}

.fzHkqk_form1 {
    .el-form-item:nth-child(5) {
        width: 100% !important;
    }
}
</style>